package com.generic.action;

import java.io.File;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.util.ServletContextAware;
import org.hibernate.HibernateException;

import com.generic.ds.HibernateSession;
import com.generic.handler.impl.ImageHandler;
import com.generic.module.impl.Member;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PhotoUpload extends ActionSupport implements ServletContextAware {

	private static final long serialVersionUID = -4149403212439528824L;
	private ServletContext servletContext;
	private File[] uploads;
	private String[] uploadFileNames;
	private String[] uploadContentTypes;

	public File[] getUpload() {
		return uploads;
	}

	public String[] getUploadFileName() {
		return uploadFileNames;
	}

	public String[] getUploadContentType() {
		return uploadContentTypes;
	}

	public void setUpload(File[] uploads) {
		this.uploads = uploads;
	}

	public void setUploadFileName(String[] uploadFileNames) {
		this.uploadFileNames = uploadFileNames;
	}

	public void setUploadContentType(String[] uploadContentTypes) {
		this.uploadContentTypes = uploadContentTypes;
	}
	
	@Override
	public void setServletContext(ServletContext context) {
		this.servletContext = context;
	}
	
	public String execute() {		
		return SUCCESS;
	}
	
	@Action(value = "/photo-upload-add", results = {
			@Result(name = "success", location = "photo-manage.jsp") })
	public String add() {
		Map<String, Object> session = ActionContext.getContext().getSession();
		Member member = (Member)session.get("MEMBER");
		HibernateSession hs = new HibernateSession();
		try {
			hs.beginTransaction();
			ImageHandler ih = new ImageHandler(hs);
			String filePath = servletContext.getRealPath("/") + "photos";
			ih.add(member.getId(), filePath, uploads, uploadFileNames);
			hs.commitTransaction();
		} catch (HibernateException e) {
			hs.rollbackTransaction(e);
		} finally {
			hs.closeSession();
		}

		return SUCCESS;
	}
}
